'''
Created on Mar 23, 2013

@author: Petko
'''
from django.views.generic.base import View
from sent.utils import createValidToken, CommonResult, ErrorIds
from sent.utils.result_printer import getPrinter
from sent.model.OpinionDBManager import OpinionDBManager
from sent.model.entities.opinion import OpinionState

class UpdateBaseOpinion(View):
    '''
    classdocs
    '''


    def __init__(self):
        '''
        Constructor
        '''
        pass
    
    def post(self, *args, **kwargs):
        accessTokenStr = self.request.POST.get('access_token', None)
        opinionId = self.request.POST.get('opinion_id', None)
        title = self.request.POST.get('title', None)
        content = self.request.POST.get('content', None)
        opinion_data = self.request.POST.get('opinion_data', None)
        
        cResult = CommonResult()
        
        if accessTokenStr and opinionId and (title or content or opinion_data):
            
            accessToken, error = createValidToken(accessTokenStr)
            if accessToken:
                dbMan = OpinionDBManager(False)
                try:
                    op = dbMan.get_opinion_by_id_str(opinionId, lockmode = 'update', allowed_states=None)
                    if op.getCreatorUUID() == accessToken.getOwnerUUID():
                        try:
                            textData = dbMan.getOpinionTextData(opinionId)
                            if title:
                                textData.title = title
                            if content:
                                textData.content = content
                            if opinion_data:
                                textData.opinion_data = opinion_data
                            
                            dbMan.update_op_text_data(textData)
                            dbMan.commitSession()
                        except:
                            dbMan.dbSession.rollback()
                            raise
                    else:
                        cResult.errorId = ErrorIds.UNAUTHORIZED
                        cResult.result = "Need to be owner of the opinion to update it"
                finally:
                    dbMan.closeSession()
            else:
                cResult.errorId = ErrorIds.UNAUTHORIZED
                cResult.result = error
        else:
            cResult.errorId = ErrorIds.BADREQUEST
            cResult.result = "Missing parameter"
            
        return getPrinter().printResult(cResult)
    
    